<template>
  <a-select show-search :allowClear="allowClear"  :mode="mode" @popupScroll="handlePopupScroll" option-filter-prop="children"
    v-model="checkedValue"  :placeholder="placeholders" @search="search" @change="changeValue">
    <a-select-option v-for="item in list" :key="item[keys]" :value="item[keys]">{{ item[label] }}
    </a-select-option>
  </a-select>
</template>
<script>
export default {
  name: 'selectLazy',
  props: {
    allowClear: {
      type: Boolean,
      default: true
    },
    pageSize: {
      type: Number,
      default: 10
    },

    searchType: {
      type: String,
      default: 'name'
    },
    placeholders: {
      type: String
    },
    mode: {
      type: String,
      default: 'default'
    },
    list: {
      type: Array,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: []
    },
    keys: {
      type: String,
      default: 'id'
    },
    label: {
      type: String,
      default: 'name'
    }
  },
  data () {
    return {
      pageIndex: 1,
      checkedValue: undefined,
      searchString: undefined,
      searchTimer: null
    }
  },
  created () {
    if (this.mode === 'multiple') {
      this.checkedValue = []
    }
    this.getList()
  },
  methods: {
    clearSelection () {
      this.checkedValue = undefined
    },
    changeValue (changeValue) {
      this.$emit('changeValue', changeValue)
    },
    handlePopupScroll (e) {
      const { scrollHeight, scrollTop, clientHeight } = e.target
      if (scrollHeight - scrollTop === clientHeight) {
        this.pageIndex++
        this.getList()
      }
    },
    search (val) {
      const self = this
      this.searchString = val
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      this.pageIndex = 1
      this.searchTimer = setTimeout(() => {
        self.getList()
      }, 500)
    },
    getList () {
      const data = {
        page_size: this.pageSize,
        page_index: this.pageIndex
      }
      if (this.searchString) {
        data[this.searchType] = this.searchString
      }

      this.$emit('getList', data)
    }
  }
}
</script>
